package cn.getech.data.development.utils.hadoop;

import cn.getech.data.development.utils.shell.ExecuteShellUtil;
import cn.getech.data.intelligence.common.utils.DateUtils;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.google.common.base.Objects;
import com.jcraft.jsch.JSchException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

@Slf4j
public class KillSparkTaskUtils {

    public static void killSparkTasks(List<String> appIds,String ip, Integer port, String username, String password,Integer jobId,Integer type) {
        if(CollectionUtil.isNotEmpty(appIds)){
            //连接到服务器
            ExecuteShellUtil resShell = ExecuteShellUtil.getInstance();
            try {
                resShell.init(ip, port,
                        username, password);
            } catch (JSchException e) {
                e.printStackTrace();
                log.error("connect linux ip:{},port:{},username:{},pwd:{} error:{}",ip,port,username,password,e.getMessage());
                resShell.close();
                return;
            }
            String tmpPaths = "/tmp/killsh";
            String killcmd = "yarn application -kill ";
            StringBuilder sb = new StringBuilder();
            sb.append("source /etc/profile\n");
            Integer num = 0;
            for (String appId : appIds) {
                num++;
                String exKillShell = killcmd + appId;
                sb.append(exKillShell).append("\n");
                log.error("kill spark shell:{},currentTime:{}",exKillShell, DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
            }
            //上传并且执行文件
            try {
                String imdds = Objects.equal(type,2) ? "killDepShell_" : "killJobShell_";
                String fileName = imdds + jobId +"_"+ DateUtils.format(new Date(),DateUtils.DATE_PATTERN_NO_FMATE_TIME) + ".sh";
                String filePath = tmpPaths +  "/" + fileName;
                resShell.uploadFile(sb.toString(), filePath);
                resShell.execCmd("cd " + tmpPaths + " && sh " + fileName);
                ThreadUtil.sleep(num*2000);
                resShell.close();
            }catch (Exception e){
                log.error("kill spark shell:{},error:{}",sb.toString(), e.getMessage());
            }
            System.out.println(sb.toString());
        }
    }
}
